package cn.rwklyd.BookKeeping.util;

import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.ImageBatchModerationRequest;
import com.aliyun.green20220302.models.ImageBatchModerationResponse;
import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.tea.TeaException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

@Component
public class ImageModerationUtil {

    private final Client client;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public ImageModerationUtil() throws Exception {
        this.client = createClient();
    }

    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5tFmzd1mPxB95bkRnrS2") // 直接硬编码AccessKeyId
                .setAccessKeySecret("6Q7a3A2dqarnI1Q84uaMJgHBxJkbaO"); // 直接硬编码AccessKeySecret
        config.endpoint = "green-cip.cn-shanghai.aliyuncs.com";
        return new Client(config);
    }

    public String moderateImage(String imageUrl, String dataId) {
        ImageBatchModerationRequest request = new ImageBatchModerationRequest()
                .setService("baselineCheck")
                .setServiceParameters(String.format("{ \"imageUrl\": \"%s\", \"dataId\": \"%s\" }", imageUrl, dataId));
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            ImageBatchModerationResponse response = client.imageBatchModerationWithOptions(request, runtime);
            ImageBatchModerationResponseBody responseBody = response.getBody();
            // 将响应体转换为JSON字符串
            return objectMapper.writeValueAsString(responseBody);
        } catch (TeaException error) {
            return "Error: " + error.getMessage() + ", Recommendation: " + error.getData().get("Recommend");
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            return "Error: " + error.getMessage() + ", Recommendation: " + error.getData().get("Recommend");
        }
    }
}